<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\QqrdController;
use App\Http\Controllers\Resource\YrdController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceQqrd;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceTypeYrd;
use App\Models\ResourceYrd;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 元阅读 数据同步
 */
class YrdMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:YrdMysqlData
    // 若使用 linux 后台执行则使用  nohup php artisan command:YrdMysqlData &   //输入完后，关闭命令行


    protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //同步资源开始页，默认为 1
    protected $resource_business_id = 9; //资源商id
    protected $down_month = 1; //下架数据，同步几个月前的数据，默认是 3 个月之内的数据
    protected $other_month = 1; //其他数据，同步几个月前的数据，默认是 3 个月之内的数据

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:YrdMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步元阅读数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {;
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('yrdcmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步数据
            $obj = new YrdController();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $resourceModel = new ResourceYrd();
            $resourceTypeYrdModel = new ResourceTypeYrd();

            // $get_type_list = $obj->getResourceType(); //获取所有分类
            // //全部先放入我们自己的服务器
            // if ($get_type_list) {
            //     $resourceTypeyrdModel = new ResourceTypeyrd();
            //     $resourceTypeyrdModel->addData($get_type_list);
            // }

            //数据太多，可能会导致更新到一半断掉
            $request_page =  $resource_business_name_info['request_page'];
            $request_time =  $resource_business_name_info['request_time'];
            if (!empty($request_page)) {
                $this->up_start_page = $request_page; //更新上架页数
            }

            $node = 1; //全更新  2 增量更新
            if ($request_time && $request_page == 1) {
                $node = 2;
                $this->up_start_page = 1; //重置成 1；//增量都是从第一页开始
            }
            //1为 电子书  2 为有声书
            for ($ii = 1; $ii <= 2; $ii++) {
                $book_type = $ii == 1 ? 'EPUB' : 'MP3'; //1为 电子书  2 为有声书
                if ($node == 2) {
                    Log::channel('yrdcmdlog')->debug('正在处理增量同步上架 ' . $book_type . ' 数据');

                    //走增量数据
                    $total_data = $obj->getResourceIncreaseList($book_type, date('Y-m-d', strtotime("-" . $this->other_month . " month", strtotime($request_time))), date('Y-m-d'));
                    if ($total_data) {
                        $result_id = '';

                        // 按 100 个元素分割
                        $total_data = array_chunk($total_data['data'], 100);
                        foreach ($total_data as $va) {
                            //获取详情
                            $resource_list = $obj->getResourceDetail($va);
                            //获取详情添加到数据库
                            foreach ($resource_list['data'] as $key => $val) {
                                //删除指定的值
                                //  unset($data_unique_id_all[$val['Id']]);
                                $yrd_class_id = $val['categorys'];
                                $yrd_class_id = empty($yrd_class_id) ? [] : $yrd_class_id;
                                foreach ($yrd_class_id as $k => $v) {
                                    //获取我们系统对应的分类id信息
                                    $self_type_info = $resourceTypeYrdModel->where('original_id', $v['id'])->where('is_del', 1)->first();
                                    $type_id = '';
                                    if (empty($self_type_info)) {
                                        $resourceTypeYrdModel->getTypeNameNoAdd($v);
                                        $type_external_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                            'name' => $v['name'],
                                            'level' => $v['treeGrade'],
                                            'resource_business_id' => $this->resource_business_id,
                                            'big_type_id' => $ii,
                                            'original_id' => $v['id'],
                                        ]);
                                    }
                                    //$type_id 只获取第一个
                                    if (empty($type_id)) {
                                        if (empty($type_external_id)) {
                                            $type_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                                'name' => $v['name'],
                                                'level' => $v['treeGrade'],
                                                'resource_business_id' => $this->resource_business_id,
                                                'big_type_id' => $ii,
                                                'original_id' => $v['id'],
                                            ]);
                                        } else {
                                            $type_id = $type_external_id;
                                        }
                                    }
                                }
                                $val['type_id'] = $type_id ?? null; //获取书籍小类
                                $val['big_type_id'] = $ii; //大类  与资源管理系统一致
                                $val['data_unique_id'] = $val['id']; //获取书籍小类
                                $result = $resourceModel->addData($val);
                                $result_id .= $result . '、';
                            }
                        }
                        Log::channel('yrdcmdlog')->debug('增量同步上架 ' . $book_type . ' 数据，处理完毕: ' . $result_id);
                    } else {
                        Log::channel('yrdcmdlog')->debug('增量同步上架 ' . $book_type . ' 数据，暂无可处理的数据');
                    }
                } else {
                    Log::channel('yrdcmdlog')->debug('正在处理全量同步上架 ' . $book_type . ' 数据');

                    if ($ii == 2) $this->up_start_page = 1; //如果是有声书，则一直都从第一页开始同步，因为有声书数量有限，不做分页处理了
                    //全同步
                    $total_data = $obj->getResourceList($book_type, 1, 1);
                    if ($total_data) {
                        $limit = $this->limit;
                        $total = $total_data['data']['total'];
                        $total_page = (int)ceil($total / $limit) + 1;

                        Log::channel('yrdcmdlog')->debug('全量同步上架 ' . $book_type . ' 数据开始，共' . $total_page . ' 页');

                        for ($i = $this->up_start_page; $i <= $total_page; $i++) {
                            //全同步
                            $data = $obj->getResourceList($book_type, $i, $limit);
                            if ($data) {
                                $result_id = '';

                                //获取详情，
                                $resource_list = $obj->getResourceDetail($data['data']['records']);
                                if (!empty($resource_list['data'])) {
                                    foreach ($resource_list['data'] as $key => $val) {
                                        //删除指定的值
                                        //  unset($data_unique_id_all[$val['Id']]);
                                        $yrd_class_id = $val['categorys'];
                                        $yrd_class_id = empty($yrd_class_id) ? [] : $yrd_class_id;
                                        foreach ($yrd_class_id as $k => $v) {
                                            //获取我们系统对应的分类id信息
                                            $self_type_info = $resourceTypeYrdModel->where('original_id', $v['id'])->where('is_del', 1)->first();
                                            $type_id = '';
                                            if (empty($self_type_info)) {
                                                $resourceTypeYrdModel->getTypeNameNoAdd($v);
                                                $type_external_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                                    'name' => $v['name'],
                                                    'level' => $v['treeGrade'],
                                                    'resource_business_id' => $this->resource_business_id,
                                                    'big_type_id' => $ii,
                                                    'original_id' => $v['id'],
                                                ]);
                                            }
                                            //$type_id 只获取第一个
                                            if (empty($type_id)) {
                                                if (empty($type_external_id)) {
                                                    $type_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                                        'name' => $v['name'],
                                                        'level' => $v['treeGrade'],
                                                        'resource_business_id' => $this->resource_business_id,
                                                        'big_type_id' => $ii,
                                                        'original_id' => $v['id'],
                                                    ]);
                                                } else {
                                                    $type_id = $type_external_id;
                                                }
                                            }
                                        }
                                        $val['type_id'] = $type_id ?? null; //获取书籍小类
                                        $val['big_type_id'] = $ii; //大类  与资源管理系统一致
                                        $val['data_unique_id'] = $val['id']; //获取书籍小类
                                        $result = $resourceModel->addData($val);
                                        $result_id .= $result . '、';
                                    }
                                }
                                //增量不更新页数,有声书也不更新，只更新电子书
                                if ($node == 1 && $ii == 1) {
                                    $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => $i + 1]); //更新页数
                                }

                                Log::channel('yrdcmdlog')->debug('全量同步上架 ' . $book_type . ' 数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                            } else {
                                //同步到最后一页才重置
                                if ($i == $total_page && $node == 1 && $ii == 1) {
                                    $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['request_page' => 1, 'request_time' => date('Y-m-d H:i:s')]); //重置页数
                                }
                                //数据太大才判断，数据量小不判断，主要解决接口莫名失败的情况
                                if ($i == $total_page) {
                                    Log::channel('yrdcmdlog')->debug('全量同步上架 ' . $book_type . ' 数据处理完毕: 页数: ' . $i);
                                } else {
                                    Log::channel('yrdcmdlog')->debug('全量同步上架 ' . $book_type . ' 数据出现异常: 页数: ' . $i);
                                }
                                break;
                            }
                        }
                    } else {
                        Log::channel('yrdcmdlog')->debug('全量同步上架 ' . $book_type . ' 数据，暂无可处理的数据');
                    }
                }
            }
            //获取数据下架列表
            //1为 电子书  2 为有声书
            for ($ii = 1; $ii <= 2; $ii++) {
                $book_type = $ii == 1 ? 'EPUB' : 'MP3'; //1为 电子书  2 为有声书

                Log::channel('yrdcmdlog')->debug('正在处理同步下架 ' . $book_type . ' 数据');

                $down_total_data = $obj->downResourceList($book_type, date('Y-m-d', strtotime("-" . $this->down_month . " month")), date('Y-m-d'));
                if ($down_total_data) {
                    //直接删除数据
                    $result_id = '';
                    $del_id = $resourceModel->deleteData($book_type, $down_total_data['data']);
                    $result_id .= $del_id . '、';

                    Log::channel('yrdcmdlog')->debug('同步下架 ' . $book_type . ' 数据，处理完毕: ' . $result_id);
                } else {
                    Log::channel('yrdcmdlog')->debug('同步下架 ' . $book_type . ' 数据，暂无可处理的数据');
                }
            }
            //更细数据列表
            for ($ii = 1; $ii <= 2; $ii++) {
                $book_type = $ii == 1 ? 'EPUB' : 'MP3'; //1为 电子书  2 为有声书

                Log::channel('yrdcmdlog')->debug('正在处理更新同步上架 ' . $book_type . ' 数据');

                //走更新数据
                $total_data = $obj->changeResourceList($book_type, date('Y-m-d', strtotime("-" . $this->other_month . " month", strtotime($request_time))), date('Y-m-d'));
                if ($total_data) {
                    $result_id = '';

                    // 按 100 个元素分割
                    $total_data = array_chunk($total_data['data'], 100);
                    foreach ($total_data as $va) {
                        //获取详情
                        $resource_list = $obj->getResourceDetail($va);
                        //获取详情添加到数据库
                        foreach ($resource_list['data'] as $key => $val) {
                            //删除指定的值
                            //  unset($data_unique_id_all[$val['Id']]);
                            $yrd_class_id = $val['categorys'];
                            $yrd_class_id = empty($yrd_class_id) ? [] : $yrd_class_id;
                            foreach ($yrd_class_id as $k => $v) {
                                //获取我们系统对应的分类id信息
                                $self_type_info = $resourceTypeYrdModel->where('original_id', $v['id'])->where('is_del', 1)->first();
                                $type_id = '';
                                if (empty($self_type_info)) {
                                    $resourceTypeYrdModel->getTypeNameNoAdd($v);
                                    $type_external_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                        'name' => $v['name'],
                                        'level' => $v['treeGrade'],
                                        'resource_business_id' => $this->resource_business_id,
                                        'big_type_id' => $ii,
                                        'original_id' => $v['id'],
                                    ]);
                                }
                                //$type_id 只获取第一个
                                if (empty($type_id)) {
                                    if (empty($type_external_id)) {
                                        $type_id = $resourceTypeExternalModel->getTypeNameNoAdd([
                                            'name' => $v['name'],
                                            'level' => $v['treeGrade'],
                                            'resource_business_id' => $this->resource_business_id,
                                            'big_type_id' => $ii,
                                            'original_id' => $v['id'],
                                        ]);
                                    } else {
                                        $type_id = $type_external_id;
                                    }
                                }
                            }
                            $val['type_id'] = $type_id ?? null; //获取书籍小类
                            $val['big_type_id'] = $ii; //大类  与资源管理系统一致
                            $val['data_unique_id'] = $val['id']; //获取书籍小类
                            $result = $resourceModel->addData($val);
                            $result_id .= $result . '、';
                        }
                    }
                    Log::channel('yrdcmdlog')->debug('更新同步上架 ' . $book_type . ' 数据，处理完毕: ' . $result_id);
                } else {
                    Log::channel('yrdcmdlog')->debug('更新同步上架 ' . $book_type . ' 数据，暂无可处理的数据');
                }
            }

            Log::channel('yrdcmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('yrdcmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
